// 转发其他模块
export * from './date'
export * from './dom'
export { default as storage } from './storage'

export const isObject = v => v !== null && typeof v === 'object'

/**
 * 将歌手列表格式化为 a/b/c 的形式
 * @param {array} ar
 * @returns string
 */
export const formatArtists = ar => {
  return ar.map(v => v.name).join('/')
}

/**
 * 节流函数
 * @param {function} fn
 * @param {number} wait
 * @returns function
 */
export function throttle (fn, wait) {
  let timer = null
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, wait)
    }
  }
}

/**
 * 防抖函数
 * @param {function} fn
 * @param {number} wait
 * @param {boolean} immediate
 * @returns function
 */
export function debounce (fn, wait, immediate) {
  let timer = null
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }

    if (immediate) {
      if (!timer) {
        fn.apply(this, args)
      }
      timer = setTimeout(() => {
        timer = null
      }, wait)
    } else {
      timer = setTimeout(() => {
        fn.apply(this, args)
      }, wait)
    }
  }
}

/**
 * 将数组分割为二维数组，它的子数组最大元素数为 num
 * @param {array} arr
 * @param {number} num
 */
export const groupByNum = (arr, num) => {
  if (!(typeof Array.isArray(arr)) || typeof num !== 'number') {
    throw new Error('Parameter Error!')
  }

  const len = arr.length
  if (num >= len) {
    return arr
  }

  const res = []
  let start = 0
  while (start < len) {
    res.push(arr.slice(start, start + num))
    start += num
  }

  return res
}

/**
 * 延迟执行，测试请求时的 loading 组件的状态
 * @param {Number} delay
 * @param {Function} cb
 */
export const delayCall = (delay, cb) => {
  setTimeout(() => {
    cb()
  }, delay)
}

/**
 * 格式化次数
 * @param {Number} count
 */
export const formatCount = count => {
  if (count > 100000000) {
    return `${Math.floor(count / 100000000)}亿`
  } else if (count > 100000) {
    return `${Math.floor(count / 10000)}万`
  }
  return count
}

export const upper = val => val.toUpperCase()
export const upperFirst = val => val.replace(/\w/, v => v.toUpperCase())

export default {}
